<script setup lang="ts">
import CdlTable from "@/components/table";
import CdlForm from "@/components/form"
import type{TableTree} from "@/interfaces/components/Table";
import type {Dist} from "@/interfaces/views/sys/dist"
import type {FormTree} from "@/interfaces/components/Form";
import type {State, Request, Query, FormData, Mode} from "@/interfaces/components/Page"
import {reactive, h, ref} from "vue";
import {useTablePagingTemplate} from "@/hooks/TableHooks";
import {createPopup} from "@/utils/createPopup";
import CdlSearch from "@/components/search";
import {createDrawer} from "@/utils/createDrawer";
import DictConfig from "@/views/sys/dict/dictConfig.vue";
import {useFormTemplate} from "@/hooks/formHooks";
import {ElMessageBox, ElTable} from "element-plus";
import type { Action } from 'element-plus'

/**
 * 请求配置
 */
const request:Request = {
  createdIsNeed: true,
  url: "/sys/dict/type"
}
const tableRef = ref<InstanceType<typeof ElTable>>()
/**
 * 表格组件模板
 */
const tabTree: TableTree<Dist> = {
  colRule: [
    {type: "selection", width: 55},
    {ti: "字典类型", prop: "dictType", sort: true, minWidth: 150},
    {ti: "字典名称", prop: "dictName", sort: true, width: 200},
    {ti: "备注", prop: "remark", tooltip: true, width: 500},
    // {ti: "数据来源", prop: "dictSource"},
    {ti: "排序", prop: "sort"},
    {ti: "创建时间", prop: "createTime", sort: true, minWidth: 160},
  ],
  control:[
    {name: "字典配置", type: "info", prop: "id", method: openDictConfig},
    {name: "修改", type: "success", method: openDictUpdate},
    {name: "删除", type: "danger", prop: "id", method: delDict},
  ]
}
/**
 * 表单组件模板
 */
const formTree: FormTree<Dist> = [
  [
    {component: "input", prop: "dictType", label: "字典类型", rule: [{
        required: true, message: '字典类型不能为空', trigger: 'blur'
      }]},
    {component: "input", prop: "dictName", label: "字典名称", rule: [{
        required: true, message: '字典类型不能为空', trigger: 'blur'
      }]},
   ],
    [
      {component: "inputNumber", prop: "sort", label: "排序"},
      {component: "radioButton", prop: "dictSource", label: "数据来源", options: [
          {label: "字典数据", value: 0},
          {label: "动态Sql", value: 1}
        ], rule: [{
          required: true, message: '字典类型不能为空', trigger: 'blur'
        }]},
    ],
    [
      {component: "input", type: "textarea", prop: "remark", label: "备注"},
    ]
]
/**
 * 搜索组件模板
 */
const searchTree: FormTree<Dist> = [
  [
    {component: "input", prop: "dictType", label: "字典类型"},
    {component: "input", prop: "dictName", label: "字典名称"},
  ]
]
/**
 * 主要数据
 */
const state = reactive<State<Query<Dist>, Dist>>({
  queryForm: {
    dictType: "",
    dictName: ""
  },
  dataList: []
})
/**
 * 弹出层数据
 */
const popupData: FormData<Dist> = {
  dictType: "",
  dictName: "",
  sort: 0,
  dictSource: 0,
  remark: ""
}
/**
 * 打开字典配置页面
 * @param id
 */
function openDictConfig(id: number){
  createDrawer(`字典配置`, h(DictConfig, {
    dictTypeId: id
  }),()=>{})
}
/**
 * 打开字典修改页面
 * @param data
 */
function openDictUpdate(data: Dist){
  createPopup("修改", h(CdlForm, {
    templateTree: formTree,
    model: createPopupDataTemplate(data)
  }), "update", popupCallBack)
}

/**
 * 打开字典新增页面
 */
function openDictIncrease(){
  createPopup("新增", h(CdlForm, {
    templateTree: formTree,
    model: createPopupDataTemplate()
  }), "add", popupCallBack)
}

/**
 * 删除字典
 * @param id
 */
function delDict(id: string | number){
  ElMessageBox.alert('在您执行删除操作前，请确认已与管理人员沟通并已知晓可能出现的异常情况？' +
      '此操作可能会导致某些数据的格式转化出现异常情况！', '警告', {
    confirmButtonText: '确认，我已知晓',
    callback: (action: Action) => {
      if(action === "confirm") batchDel(id)
    }
  })
}

function multipleSelectionDel(){
  const selectList = tableRef.value!
  if("multipleSelection" in selectList){
    ElMessageBox.alert('在您执行删除操作前，请确认已与管理人员沟通并已知晓可能出现的异常情况？' +
        '此操作可能会导致某些数据的格式转化出现异常情况！', '警告', {
      confirmButtonText: '确认，我已知晓',
      callback: (action: Action) => {
        // @ts-ignore
        if(action === "confirm") batchDel(selectList.multipleSelection.map(item => item.id))
      }
    })
  }else throw new Error("未知异常")
}
/**
 * 组件回调事件
 * @param data   数据
 * @param mode  模式
 */
function popupCallBack(mode: Mode, data?: any){
  console.log(data, mode)
  switch (mode){
    case "search":
      query(data)
          break
    case "resetting":
      query()
          break
    case "add":
      added(data)
      break
    case "update":
      update(data)
      break
  }
}



const {query, added, batchDel, update, loading, handleSizeChange, handleCurrentChange}
    = useTablePagingTemplate(request, state)
const {createPopupDataTemplate} = useFormTemplate(popupData)
</script>

<template>
  <el-card>
    <CdlSearch :template-tree="searchTree" :model="state.queryForm" @submit="popupCallBack">
      <template #menu>
        <el-button type="primary" @click="openDictIncrease">新增</el-button>
        <el-button type="danger" @click="multipleSelectionDel">批量删除</el-button>
      </template>
    </CdlSearch>
    <CdlTable :template-tree="tabTree" :data="state.dataList" ref="tableRef"
              :controlWidth="300" :loading="loading" controlFixed></CdlTable>
    <el-pagination
        :current-page="state.page"
        :page-sizes="state.pageSizes!"
        :page-size="state.limit"
        :total="state.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    >
    </el-pagination>
  </el-card>
</template>

<style scoped lang="scss">
div{
  text-align: center;
}
</style>
